package si.yun.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @ClassName ipUtils
 * @Author SXM
 * @Date 2021/07/30 14:01
 * @Version 1.0
 */
public class ipUtils {
    /*
     * @Author SXM
     * @Description //获取IP地址（linux 和 window 通用）
     * @return java.lang.String
     * @Date 2021/7/30  14:02
     **/
    @SuppressWarnings("rawtypes")
    public static String getIP() {
        String ipStr = "";
        Enumeration allNetInterfaces = null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            System.err.println("发生异常");
        }
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
                    .nextElement();
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    ipStr = ip.getHostAddress();
                }
            }
        }
        return ipStr;
    }
}
